package com.shop.admin.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.shop.admin.config.JwtUtils;
import com.shop.admin.model.po.Admins;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author 'banxia'
 * @version 1.0
 * @description 拦截器获取merchant
 * @date 2023/2/21 23:40
 */
@Slf4j
public class GetAdminsInfoInterceptor implements HandlerInterceptor {

    private static boolean flag=false;//用来表示是否有储存数据到threadLoacl

    //请求进入前先判断是否存在token，若存在尝试转换为merchant对象，转换merchant对象抛出错误就拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getHeader("token");
            if (token != null) {
                String adminsJson = JwtUtils.getAdminByJwtToken(token);
                //若token存在，那么其经过网关就是合法的！
                Admins admins = JSONObject.parseObject(adminsJson, Admins.class);
                //判断是否为merchant类型，若不是的话就是越权，要抛出异常
                String type = admins.getType();
                if (!"admins".equals(type)){
                    throw new Exception("该token并非是admins的token");
                }
                //将得到的merchant储存到ThreadLocal中
                threadLocal.set(admins);
                flag=true;
            }
        } catch (Exception e) {
            log.error("token转对象储存到本地失败,异常：{}",e.getMessage());
            return false;
        }
        return true;
    }

    //删除threadLocal中的数据
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (flag) threadLocal.remove();
        flag=false;
    }

    private static final ThreadLocal<Admins> threadLocal=new ThreadLocal<>();

    public static Admins getAdmins() {
        if (!flag) return null;
        return threadLocal.get();
    }

    private static void removeAdmins() {
        if (flag) threadLocal.remove();
        flag=false;
    }
}
